import UIKit
import FastSwiftSDK
import CoreMotion

class PlayViewController: UIViewController {

    private lazy var directionView: DirectionView_360 = {
        let view = DirectionView_360(frame: kFrame(20, 0, 300, 300))
        view.cornerRadius = 150
        view.centerY = self.view.centerY
        view.callBack = { num in
            
            print("角度----------\(num)")
            
        }
        return  view
    } ()
    
    let motionManager = CMMotionManager()
    var currentAngle: Double = 0.0 // 当前角度，单位为度

    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view.addSubview(directionView)
        
        if motionManager.isGyroAvailable {
            motionManager.gyroUpdateInterval = 1
            motionManager.startAccelerometerUpdates(to: .main) { [weak self] (data, error) in
                guard let accelerometerData = data else { return }
                self?.updateLevelFromAccelerometer(accelerometerData)
            }
        }
    }
    
    private func updateLevelFromAccelerometer(_ accelerometerData: CMAccelerometerData) {
        let acceleration = accelerometerData.acceleration
        
        // 计算X轴和Y轴的角度
        let roll = atan2(acceleration.x, sqrt(acceleration.y * acceleration.y + acceleration.z * acceleration.z))
        let pitch = atan2(acceleration.y, sqrt(acceleration.x * acceleration.x + acceleration.z * acceleration.z))
        
        // 将弧度转换为角度
        let y = roll * 180 / .pi
        let x = pitch * 180 / .pi
        
   
        // 更新LevelView
        DispatchQueue.main.async { [weak self] in
            self?.directionView.updateBtn(Float(x), Float(y))
//            self.levelView.update(roll: rollDegrees, pitch: pitchDegrees)
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
//        directionView.snp.makeConstraints { make in
//            make.left.equalToSuperview().offset(50)
//            make.size.equalTo(300)
//            make.centerY.equalToSuperview()
//        }
        
    }

}

// 方向按钮视图
class DirectionView_360: FastView{
    
    var callBack:FastIntBlock?
    let maxRadius: CGFloat = 100
    private lazy var bgView: FastView = {
        let view = FastView(frame: self.bounds)
        view.backgroundColor = .lightGray
        view.alpha = 0.3
        view.cornerRadius = self.width/2
        return  view
    } ()
    
    private lazy var directionButton: UIButton = {
        let btn = UIButton(type: .system)
        btn.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        btn.center = CGPoint(x: self.width/2, y: self.height/2)
//        btn.setTitle("⬤", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
        btn.layer.cornerRadius = 50
        btn.backgroundColor = .hex("#CAAD00")
        return  btn
    } ()
    
    override func setupUI() {
        
        self.addSubview(bgView)
        self.addSubview(directionButton)
        
        // 添加手势识别
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        panGesture.addTarget(self, action: #selector(handlePanEnded(_:)))
        self.addGestureRecognizer(panGesture)
    }

    @objc func handlePan(_ gesture: UIPanGestureRecognizer) {
        let touchLocation = gesture.location(in: self)
        let center = directionButton.center

        // 计算与中心的距离
        let distance = hypot(touchLocation.x - center.x, touchLocation.y - center.y)

        // 限制最大半径
        if distance <= maxRadius {
            directionButton.center = touchLocation
        } else {
            // 计算限制后的坐标
            let angle = atan2(touchLocation.y - center.y, touchLocation.x - center.x)
            let limitedX = center.x + maxRadius * cos(angle)
            let limitedY = center.y + maxRadius * sin(angle)
            directionButton.center = CGPoint(x: limitedX, y: limitedY)
        }

        angleInDegrees()
    }

    @objc func handlePanEnded(_ gesture: UIPanGestureRecognizer) {
        if gesture.state == .ended {
            // 动画回到默认原点
            UIView.animate(withDuration: 0.3) {
                self.directionButton.center = CGPoint(x: self.width/2, y: self.height/2)
            }
        }
    }
    
    func angleInDegrees(){
        // 计算角度并输出（12点方向为0度）
        let adjustedCenter = CGPoint(x: self.width/2, y: self.height/2)
        var angleInDegrees = atan2(directionButton.center.y - adjustedCenter.y, directionButton.center.x - adjustedCenter.x) * (180 / .pi)
        angleInDegrees = (angleInDegrees + 90).truncatingRemainder(dividingBy: 360) // 确保12点为0度
        if angleInDegrees < 0 {
            angleInDegrees += 360 // 确保角度为正数
        }
        self.callBack?(Int(angleInDegrees))
        print("当前滑动方向角度: \(angleInDegrees)°")
    }
    
    func updateBtn(_ x:Float,_ y:Float){
        if x > 0 {
            directionButton.centerX = 150 - CGFloat(abs(x))
        }else{
            directionButton.centerX = 150 + CGFloat(abs(x))
        }
        
        if y > 0 {
            directionButton.centerY = 150 - CGFloat(abs(y))
        }else{
            directionButton.centerY = 150 + CGFloat(abs(y))
        }
        
        angleInDegrees()
    }
}
